package com.ai.core.util;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
	/**
	 * 根据名称读取Cookie
	 * 
	 */
	public static String readCokie(HttpServletRequest request, HttpServletResponse response, String name) throws ServletException, IOException {
		String value = null;
		if (name != null) {
			Cookie cookies[] = request.getCookies();
			if (cookies != null && cookies.length >= 2) {
				for (int i = 0; i < cookies.length; i++) {
					Cookie cookie = cookies[i];
					if (name.equals(cookie.getName())) {
						value = cookie.getValue();
					}
				}
			}
		}
		return value;
	}

	/**
	 * 清空cookie
	 */
	public static void clearCokie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Cookie[] cookies = request.getCookies();
		for (int i = 0; i < cookies.length; i++) {
			Cookie cookie = cookies[i];
			cookie.setMaxAge(0);
			response.addCookie(cookie);
		}
	}

	/**
	 * 写Cookie
	 */
	public static void writeCokie(HttpServletResponse response, String name, String value, int days) throws ServletException, IOException {
		int day = 24 * 60 * 60;
		Cookie cookie = new Cookie(name, value);
		cookie.setMaxAge(days * day);
		response.addCookie(cookie);
	}

	 

}
